<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="名称(型号)" prop="model">
        <el-input v-model="formData.model" placeholder="请输入型号" />
      </el-form-item>
      <el-form-item label="流量计编号" prop="serialNumber">
        <el-input v-model="formData.serialNumber" placeholder="请输入序列号" />
      </el-form-item>
      <el-form-item label="流量范围">
        <el-row :gutter="20" style="width: 100%">
          <el-col :span="11">
            <el-form-item prop="minFlow" style="margin-bottom: 0px">
              <el-input v-model.number="formData.minFlow" placeholder="最小值" type="number">
                <template #append>ml/min</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="2" class="text-center" style="line-height: 40px">
            <span class="text-gray-500">至</span>
          </el-col>
          <el-col :span="11">
            <el-form-item prop="maxFlow" style="margin-bottom: 0px">
              <el-input v-model.number="formData.maxFlow" placeholder="最大值" type="number">
                <template #append>ml/min</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { FlowmeterApi, FlowmeterVO } from '@/api/system/flowmeter'
import { watch } from 'vue' // 引入 watch
import { FormInstance } from 'element-plus' // 引入 FormInstance 类型

/** 流量计 表单 */
defineOptions({ name: 'FlowmeterForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  name: undefined,
  model: undefined,
  serialNumber: undefined,
  minFlow: undefined,
  maxFlow: undefined
})

// 校验最小值
const validateMinFlow = (rule: any, value: any, callback: any) => {
  console.log('validateMinFlow called with value:', value)
  console.log('Current formData values:', {
    minFlow: formData.value.minFlow,
    maxFlow: formData.value.maxFlow
  })

  // 如果是新增模式 且 值为空/undefined/null，则提示必填
  if (formType.value === 'create' && (value === '' || value === undefined || value === null)) {
    callback(new Error('请输入流量最小值')) // 新增模式下，空值是必填错误
    return
  }
  // 如果是编辑模式 且 值为空/undefined/null，允许通过（不显示必填提示）
  if (formType.value === 'update' && (value === '' || value === undefined || value === null)) {
    console.log(
      'validateMinFlow: update mode and value is empty/null/undefined, passing required check.'
    )
    callback() // 编辑模式下，空值不触发必填错误
    // 但是，如果 maxFlow 有值，仍然需要检查交叉校验
    const maxNum = Number(formData.value.maxFlow)
    if (
      formData.value.maxFlow !== undefined &&
      formData.value.maxFlow !== null &&
      formData.value.maxFlow !== '' &&
      !isNaN(maxNum)
    ) {
      // 如果 minFlow 为空，maxFlow 不为空，且 maxFlow <= 0，也可能需要特殊处理，这里简化为只在 minFlow 不为空时检查交叉校验
      // 如果 minFlow 为空，maxFlow 不为空，不进行交叉校验，让 maxFlow 的校验函数去检查 maxFlow 的有效性
      console.log('validateMinFlow: update mode, minFlow is empty, skipping cross-validation.')
    }
    return
  }

  const num = Number(value)
  // 检查是否为有效数字
  if (isNaN(num)) {
    console.log('validateMinFlow: value is not a number, failing.')
    callback(new Error('请输入有效的数字'))
    return
  }

  // 检查是否小于0
  if (num < 0) {
    console.log('validateMinFlow: value is negative, failing.')
    callback(new Error('流量值不能小于0'))
    return
  }

  // 如果最大值已填写，检查最小值是否小于最大值
  const maxNum = Number(formData.value.maxFlow)
  // 只有当 maxFlow 也是有效数字时才进行比较
  if (
    formData.value.maxFlow !== undefined &&
    formData.value.maxFlow !== null &&
    formData.value.maxFlow !== '' &&
    !isNaN(maxNum)
  ) {
    console.log(`validateMinFlow: Comparing minFlow (${num}) >= maxFlow (${maxNum})`)
    if (num >= maxNum) {
      console.log('validateMinFlow: minFlow >= maxFlow, failing.')
      callback(new Error('最小值必须小于最大值'))
      return
    }
  } else {
    console.log(
      'validateMinFlow: maxFlow is not set, not a valid number, or empty string, skipping comparison.'
    )
  }

  console.log('validateMinFlow: passing.')
  callback()
}

// 校验最大值
const validateMaxFlow = (rule: any, value: any, callback: any) => {
  console.log('validateMaxFlow called with value:', value)
  console.log('Current formData values:', {
    minFlow: formData.value.minFlow,
    maxFlow: formData.value.maxFlow
  })

  // 如果是新增模式 且 值为空/undefined/null，则提示必填
  if (formType.value === 'create' && (value === '' || value === undefined || value === null)) {
    callback(new Error('请输入流量最大值')) // 新增模式下，空值是必填错误
    return
  }
  // 如果是编辑模式 且 值为空/undefined/null，允许通过（不显示必填提示）
  if (formType.value === 'update' && (value === '' || value === undefined || value === null)) {
    console.log(
      'validateMaxFlow: update mode and value is empty/null/undefined, passing required check.'
    )
    callback() // 编辑模式下，空值不触发必填错误
    // 如果 minFlow 有值，仍然需要检查交叉校验（尽管通常在 minFlow 校验里检查 max <= min 更常见）
    // 这里简化为只在 maxFlow 不为空时检查交叉校验
    const minNum = Number(formData.value.minFlow)
    if (
      formData.value.minFlow !== undefined &&
      formData.value.minFlow !== null &&
      formData.value.minFlow !== '' &&
      !isNaN(minNum)
    ) {
      // 如果 maxFlow 为空，minFlow 不为空，且 minFlow >= 0，也可能需要特殊处理，这里简化为只在 maxFlow 不为空时检查交叉校验
      console.log('validateMaxFlow: update mode, maxFlow is empty, skipping cross-validation.')
    }
    return
  }

  const num = Number(value)
  // 检查是否为有效数字
  if (isNaN(num)) {
    console.log('validateMaxFlow: value is not a number, failing.')
    callback(new Error('请输入有效的数字'))
    return
  }

  // 检查是否小于0
  if (num < 0) {
    console.log('validateMaxFlow: value is negative, failing.')
    callback(new Error('流量值不能小于0'))
    return
  }

  // 如果最小值已填写，检查最大值是否大于最小值
  const minNum = Number(formData.value.minFlow)
  // 只有当 minFlow 也是有效数字时才进行比较
  if (
    formData.value.minFlow !== undefined &&
    formData.value.minFlow !== null &&
    formData.value.minFlow !== '' &&
    !isNaN(minNum)
  ) {
    console.log(`validateMaxFlow: Comparing maxFlow (${num}) <= minFlow (${minNum})`)
    if (num <= minNum) {
      console.log('validateMaxFlow: maxFlow <= minFlow, failing.')
      callback(new Error('最大值必须大于最小值'))
      return
    }
  } else {
    console.log(
      'validateMaxFlow: minFlow is not set, not a valid number, or empty string, skipping comparison.'
    )
  }

  console.log('validateMaxFlow: passing.')
  callback()
}

const formRules = reactive({
  name: [{ required: true, message: '请输入流量计名称', trigger: 'blur' }],
  model: [{ required: true, message: '请输入型号', trigger: 'blur' }],
  serialNumber: [{ required: true, message: '请输入序列号', trigger: 'blur' }],
  minFlow: [{ validator: validateMinFlow, trigger: ['blur', 'change'] }],
  maxFlow: [{ validator: validateMaxFlow, trigger: ['blur', 'change'] }]
})
const formRef = ref<FormInstance>() // 表单 Ref

// 添加 watch 来手动触发交叉验证
watch(
  () => formData.value.minFlow,
  (newVal, oldVal) => {
    console.log('minFlow changed, triggering maxFlow validation')
    // 当 minFlow 改变时，触发 maxFlow 的验证
    formRef.value?.validateField('maxFlow').catch((error: any) => {
      console.log('maxFlow validation error after minFlow change (caught):', error)
    })
  }
)

watch(
  () => formData.value.maxFlow,
  (newVal, oldVal) => {
    console.log('maxFlow changed, triggering minFlow validation')
    // 当 maxFlow 改变时，触发 minFlow 的验证
    formRef.value?.validateField('minFlow').catch((error: any) => {
      console.log('minFlow validation error after maxFlow change (caught):', error)
    })
  }
)

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm() // 先重置表单，确保干净的状态

  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const result = await FlowmeterApi.getFlowmeter(id)
      // 确保数据结构符合预期，特别是 minFlow 和 maxFlow
      // 可以简单地赋值，或者根据需要进行更复杂的映射
      formData.value = result

      // 数据加载完成后，清除所有验证错误提示
      // 尤其是在编辑模式下，避免加载空值时触发必填提示
      // 使用 nextTick 确保 DOM 更新完成后再清除验证
      nextTick(() => {
        console.log('Data loaded, clearing validation...')
        formRef.value?.clearValidate(['minFlow', 'maxFlow']) // 只清除流量范围的验证
        console.log('Validation cleared for minFlow and maxFlow.')
      })
    } catch (error) {
      console.error('Failed to load flowmeter data:', error)
      message.error('加载流量计信息失败') // 添加加载失败的错误提示
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  console.log('Submitting form, performing full validation...')
  // 校验表单
  // validate() 方法会验证所有带有 prop 的 el-form-item
  const isValid = await formRef.value?.validate().catch((error) => {
    console.log('Full form validation failed:', error)
    // 如果 validation 失败，validate() 返回 false 或抛出错误
    return false // 捕获错误后返回 false
  })

  if (!isValid) {
    console.log('Form validation failed, stopping submission.')
    return // 验证失败，停止提交
  }

  console.log('Form validation successful, proceeding with submission.')
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as FlowmeterVO
    if (formType.value === 'create') {
      await FlowmeterApi.createFlowmeter(data)
      message.success(t('common.createSuccess'))
    } else {
      await FlowmeterApi.updateFlowmeter(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } catch (error) {
    console.error('API submission failed:', error)
    message.error('提交失败，请稍后再试') // 添加一个通用的错误提示
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  console.log('Resetting form...')
  // 重置 formData
  formData.value = {
    id: undefined,
    name: undefined,
    model: undefined,
    serialNumber: undefined,
    minFlow: undefined,
    maxFlow: undefined
  }
  // 重置表单项的值和验证状态
  // resetFields 方法会重置所有带 prop 的 el-form-item 的值和验证状态
  // 确保 formRef.value 存在再调用
  if (formRef.value) {
    formRef.value.resetFields()
    console.log('Form fields reset.')
  } else {
    console.log('formRef is not available yet for resetFields.')
  }
  console.log('Form reset complete.')
}
</script>
